import axios from 'axios';
import { showFailToast, showDialog } from "vant";
import Tools from '../utlis/tools';
import { toPage, isWeiXin, reLaunch } from '@/utlis/tools';
import { useStore } from "@/store"
const store = useStore();

const instance = axios.create({
    responseType: 'json',
    withCredentials: true,
    validateStatus: function (status) {
        return status >= 100 && status < 600
    },
    transformResponse: [
        function (result) {
            // 也不知道为啥，response返回都是 string，额外增加一个判断.
            // console.log(result);
            const type = Object.prototype.toString.call(result).slice(8, -1);
            const data = type === "String" ? JSON.parse(result) : result;
            if (data?.code !== 200) {
                showFailToast(data?.message)
            }
            if (data?.code === 401) {
                localStorage.removeItem("token")
                window.location.hash = "#/me?istoken=1"
            }
            return data;
        },
    ],
});

instance.interceptors.request.use((config) => {
    config.headers["token"] = `${Tools.getStorage("token")} `; //获取token
    return config;
});

export const getClient = async (url, params = {}) => {
    try {
        const { data } = await instance.get(url, { params });
        return data;
    } catch (error) {
        throw error;
    }
};
export const postClient = async (url, params = {}, method = "post") => {
    try {
        let data = null
        if (method == "post") {
            const res = await instance.post(url, params, {
                // onDownloadProgress: (p) => {
                //     console.log(1, p);
                // },
                // onUploadProgress: (p) => {
                //     console.log(2, p);
                // }
            });
            data = res.data
        } else if (method == "postJson") {
            const res = await instance.post(url, params, {
                headers: { 'Content-Type': 'application/json' },
                onDownloadProgress: (p) => {
                    console.log(1, p);
                },
                onUploadProgress: (p) => {
                    console.log(2, p);
                }
            });
            data = res.data
        }
        return data;
    } catch (error) {
        throw error;
    }
};

export default instance;